package com.mobile.ado.util.image;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class AsyncImageLoader {

	private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
	private Handler handler;

	public Drawable loadDrawable(final String imageUrl,
			final AsyncImageLoadComplete loadCompletedCallback) {

		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			if (softReference.get() != null) {
				return softReference.get();
			}

			createHandler(loadCompletedCallback);
			Thread imageDownloadThread = createImageDownloadThread(imageUrl);
			imageDownloadThread.start();
		}

		return null;
	}

	private Thread createImageDownloadThread(final String imageUrl) {
		return new Thread() {
			public void run() {

				Drawable imageDrawable = loadImageFromUrl(imageUrl);
				if (imageDrawable != null) {
					imageCache.put(imageUrl, new SoftReference<Drawable>(
							imageDrawable));

					Message message = handler.obtainMessage(0, imageDrawable);
					handler.sendMessage(message);
				}
			};
		};
	}

	private void createHandler(
			final AsyncImageLoadComplete loadCompletedCallback) {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					Drawable drawable = (Drawable) msg.obj;
					loadCompletedCallback.imageLoadCompleted(drawable);
					super.handleMessage(msg);
				}
			}
		};
	}

	private Drawable loadImageFromUrl(String imageUrl) {
		try {
			return Drawable.createFromStream(new URL(imageUrl).openStream(),
					"src");

		} catch (IOException e) {
			return null;
		}
	}

}
